package com.dgshanger.sanhxiaofeisc.ui.home

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.Utils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.dgshanger.sanhxiaofeisc.MainActivity
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.adapter.HomeAdapter
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.entity.HomeEntity
import com.dgshanger.sanhxiaofeisc.mvp.contract.HomeContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.HomePresenter
import com.dgshanger.sanhxiaofeisc.ui.WebActivity
import com.dgshanger.sanhxiaofeisc.ui.home.activity.*
import com.dgshanger.sanhxiaofeisc.ui.home.utils.GPSUtils
import com.dgshanger.sanhxiaofeisc.ui.home.utils.ImageLoader
import com.dgshanger.sanhxiaofeisc.ui.home.utils.LocationManger
import com.dgshanger.sanhxiaofeisc.ui.home.utils.TextDialog
import com.dgshanger.sanhxiaofeisc.ui.nearby.CategoryActivity
import com.dgshanger.sanhxiaofeisc.ui.nearby.CategoryListActivity
import com.dgshanger.sanhxiaofeisc.ui.nearby.SearchActivity
import com.dgshanger.sanhxiaofeisc.ui.person.SharedActivity
import com.xx.baseuilibrary.mvp.BaseMvpFragment
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import com.yzq.zxinglibrary.common.Constant
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.item_person_center.view.*
import kotlinx.android.synthetic.main.view_home_head.view.*
import kotlinx.android.synthetic.main.view_title_bar1.*
import kotlinx.android.synthetic.main.view_title_bar2.*
import kotlinx.android.synthetic.main.view_title_bar3.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * HomeFragment
 * 沉迷学习不能自拔
 * Describe：
 * Created by 雷小星🍀 on 2018/4/10 18:06.
 */
class HomeFragment : BaseMvpFragment<HomeContract.Model, HomeContract.View, HomePresenter>(), HomeContract.View, View.OnClickListener, AppBarLayout.OnOffsetChangedListener {

    val PERMISSION_REQUEST: Int = 10008
    private var mMaskColor: Int = 0
    private lateinit var mHomeAdapter: HomeAdapter
    private var currentPage: Int = 1
    private lateinit var mLocationInfo: Array<String>
    private lateinit var mLl_container: LinearLayout

    //需要检测的定位权限
    private var needPermissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,/*
            Manifest.permission.WRITE_EXTERNAL_STORAGE,*/
            /*Manifest.permission.READ_EXTERNAL_STORAGE,*/
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CHANGE_WIFI_STATE)


    override fun createPresenter(): HomePresenter = HomePresenter()

    override fun getFragmentLayoutId(): Int = R.layout.fragment_home

    override fun initView(view: View?) {
        EventBus.getDefault().register(this)
        mMaskColor = resources.getColor(R.color.colorAccent)
        rl_search.setOnClickListener(this)
        rl_scan.setOnClickListener(this)
        rl_pay_code.setOnClickListener(this)
        rl_shop_enter.setOnClickListener(this)
        rl_video.setOnClickListener(this)
        rl_share.setOnClickListener(this)
        iv_scan.setOnClickListener(this)
        iv_pay_code.setOnClickListener(this)
        iv_shop_enter.setOnClickListener(this)
        iv_video.setOnClickListener(this)
        iv_share.setOnClickListener(this)
        iv_plus.setOnClickListener(this)
        abl_bar.addOnOffsetChangedListener(this)
        rec_home.layoutManager = LinearLayoutManager(mContext)
        mHomeAdapter = HomeAdapter(ArrayList<HomeEntity.RecommendListBean>())
        mHomeAdapter.addHeaderView(getHeaderView())
        rec_home.adapter = mHomeAdapter
        mHomeAdapter.setOnLoadMoreListener {
            getPresenter().loadData(currentPage.toString(), mLocationInfo[1], mLocationInfo[0], true)
        }
    }

    override fun initData() {
        if (Constants.isLogin()) {
            ImageLoader.loadAvatar(mContext, iv_plus, Constants.getUserEntity()?.avatar)
        } else {
            iv_plus.setImageResource(R.color.colorDivler)
        }
        initSwipeRefreshLayout()
        mLocationInfo = Constants.getLocation()
        if (mLocationInfo.size == 3) {
            tv_location.text = mLocationInfo[2]
        }
        if (Constants.isFirstLogin()) {//是否第一次登录
            //第一次登录从网络获取数据,加载loading
            fl_loading.visibility = View.VISIBLE
            rec_home.visibility = View.GONE
            fl_loading.postDelayed(object : Runnable {
                override fun run() {
                    getPresenter().loadData(currentPage.toString(), mLocationInfo[1], mLocationInfo[0], false)
                }
            }, 1500)

        } else {
            //如果不是等一次登录,隐藏loading,从sp获取以前数据再重新加载数据
            fl_loading.visibility = View.GONE
            rec_home.visibility = View.VISIBLE
            setData(Constants.getHomeData(), false)
            currentPage = 2
//            getPresenter().loadData(currentPage.toString(), mLocationInfo[1], mLocationInfo[0], false)
        }
        Constants.setIsFirstLogin(false)
    }


    private fun initSwipeRefreshLayout() {
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent)
        swipeRefreshLayout.setOnRefreshListener {
            //每次刷新时重新获取头像
            if (Constants.isLogin()) {
                ImageLoader.loadAvatar(mContext, iv_plus, Constants.getUserEntity()?.avatar)
            } else {
                iv_plus.setImageResource(R.color.colorDivler)
            }

            currentPage = 1
            mLocationInfo = Constants.getLocation()
            tv_location.text = mLocationInfo[2]
            getPresenter().loadData(currentPage.toString(), mLocationInfo[1], mLocationInfo[0], false)
        }
    }

    private fun getHeaderView(): View? {
        val view = View.inflate(mContext, R.layout.view_home_head, null)
        view.tv_home_check_all.setOnClickListener(this)
        mLl_container = view.findViewById<LinearLayout>(R.id.ll_container)
        for (i in 0..2) {
            val childItemView = View.inflate(mContext, R.layout.item_person_center, null)
            childItemView.id = i
            mLl_container.addView(childItemView)
        }
        return view
    }

    override fun onClick(view: View?) {
        when (view!!.id) {

            R.id.rl_search -> {//搜索
                val intent = Intent(mContext, SearchActivity::class.java)
                startActivity(intent)
            }
            R.id.rl_scan, R.id.iv_scan -> {//扫一扫
                /*val intent = Intent(mContext, PaymentCodeActivity::class.java)
                startActivity(intent)*/
                PermissionUtils.permission(Manifest.permission.CAMERA)
                        .callback(object : PermissionUtils.SimpleCallback {
                            override fun onGranted() {
                                initZXing()
                            }

                            override fun onDenied() {
                                initZXing()
                            }

                        })
                        .rationale(object : PermissionUtils.OnRationaleListener {
                            override fun rationale(shouldRequest: PermissionUtils.OnRationaleListener.ShouldRequest?) {
                                shouldRequest!!.again(true)
                            }

                        })
                        .request()

            }
            R.id.rl_pay_code, R.id.iv_pay_code -> {//支付二维码
                val intent = Intent(mContext, PayCodeActivity::class.java)
                startActivity(intent)
            }
            R.id.rl_shop_enter, R.id.iv_shop_enter -> {//商家入驻
                val intent = Intent(mContext, EnterProtocolActivity::class.java)
                startActivity(intent)
            }
            R.id.rl_video, R.id.iv_video -> {//3h视频
                val intent = Intent(mContext, ShoppingVideoActivity::class.java)
                startActivity(intent)
            }
            R.id.rl_share, R.id.iv_share -> {//分享
                val intent = Intent(mContext, SharedActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_home_check_all -> {//查看全部类别
                val intent = Intent(mContext, CategoryListActivity::class.java)
                startActivity(intent)
            }
            R.id.iv_plus -> {//头像被点击
                val intent = Intent(mContext, MainActivity::class.java)
                intent.putExtra(Constants.KEY_INTENT_MAIN, MainActivity.INDEX_PERSON)
                startActivity(intent)
            }

        }
    }

    private fun initZXing() {
        /*val integrator = IntentIntegrator.forSupportFragment(this);//v4包Fragment
        //IntentIntegrator integrator = IntentIntegrator.forFragment(HomeFragment.this);//app包Fragment
        //IntentIntegrator integrator = IntentIntegrator(this)//activity
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        integrator.captureActivity = ScanActivity::class.java
        //integrator.setPrompt("请将二维码置于扫描框") //底部的提示文字，设为""可以置空
        integrator.setCameraId(0) //前置或者后置摄像头
        integrator.setBeepEnabled(true) //扫描成功的「哔哔」声，默认开启
        integrator.setBarcodeImageEnabled(true)
        integrator.initiateScan()*/
        val intent = Intent(mContext, CaptureActivity::class.java)
        val zxingConfig = ZxingConfig()
        zxingConfig.setPlayBeep(true)
        zxingConfig.setShake(true)
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, zxingConfig)
        startActivityForResult(intent, REQUEST_CODE_SCAN)
    }

    private var REQUEST_CODE_SCAN: Int = 10003

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PERMISSION_REQUEST) {
            requestPermission()
            return
        }
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN) {
            if (data != null) {
                var content = data.getStringExtra(Constant.CODED_CONTENT)
                val intent = Intent(mContext, PaymentCodeActivity::class.java)
                intent.putExtra("shop_number", content)
                startActivity(intent)
            } else {
                showToast(getString(R.string.Failure_to_identify))
            }
        }
        /*val intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (intentResult != null) {
            if (intentResult.contents == null) {
                showToast("未能识别")
            } else {
                val shop_number = intentResult.contents.toString()
                val intent = Intent(mContext, PaymentCodeActivity::class.java)
                intent.putExtra("shop_number", shop_number)
                startActivity(intent)
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }*/
    }


    override fun initEvent(view: View?) {
        rec_home.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                val recommendListBean = mHomeAdapter.data[position]
                val type = recommendListBean.list_type.toInt()
                when (type) {
                    1 -> {//商家
                        val intent = Intent(mContext, ShopDetailsActivity::class.java)
                        intent.putExtra("shop_id", recommendListBean.join_shop.shop_id)
                        intent.putExtra("comment_score", recommendListBean.join_shop.comment_score)
                        startActivity(intent)
                        (mContext as Activity).overridePendingTransition(R.anim.translate_in, R.anim.scale_out2)
                    }
                    2 -> {//图片
                        if (recommendListBean.join_activity_img.redirect_type.toInt() == 1) {
                            //链接
                            val intent = Intent(mContext, HomeWebActivity::class.java)
                            intent.putExtra("webUrl", recommendListBean.join_activity_img.redirect_url)
                            startActivity(intent)
                            (mContext as Activity).overridePendingTransition(R.anim.translate_in, R.anim.scale_out2)

                        } else {
                            //富文本
                            val intent = Intent(mContext, WebActivity::class.java)
                            intent.putExtra("title", recommendListBean.join_activity_img.title)
                            intent.putExtra("data", recommendListBean.join_activity_img.content)
                            startActivity(intent)
                            (mContext as Activity).overridePendingTransition(R.anim.translate_in, R.anim.scale_out2)
                        }

                    }
                    3 -> {//视频
                        val join_activity_video = recommendListBean.join_activity_video
                        if ("1".equals(join_activity_video.video_type)) {
                            //内链,视频
                            val intent = Intent(mContext, HomeVideo2Activity::class.java)
                            intent.putExtra("videoUrl", join_activity_video.video_url)
                            intent.putExtra("title", join_activity_video.title)
                            startActivity(intent)
                            (mContext as Activity).overridePendingTransition(R.anim.translate_in, R.anim.scale_out2)
                        } else if ("2".equals(join_activity_video.video_type)) {
                            //外链,web
                            val intent = Intent(mContext, WebActivity::class.java)
                            intent.putExtra("title", join_activity_video.title)
                            intent.putExtra("data", join_activity_video.video_out_link)
                            startActivity(intent)
                            (mContext as Activity).overridePendingTransition(R.anim.translate_in, R.anim.scale_out2)
                        }

                    }
                }
            }
        })

        requestPermission()
        tv_location.setOnClickListener {
            currentPage = 1
            mLocationInfo = Constants.getLocation()
            getPresenter().loadData(currentPage.toString(), mLocationInfo[1], mLocationInfo[0], false)
        }

    }

    private var isFirstShowDialog: Boolean = true
    private var isPermissionResult: Boolean = false
    private fun requestPermission() {
        Log.e("Tag", "requestPermission")
        PermissionUtils.permission(needPermissions[0], needPermissions[1], needPermissions[2]
                , needPermissions[3]/*, needPermissions[4]*//*, needPermissions[5]*/)
                .callback(object : PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        //LocationManger.getInstance().setIsSendMsg(true)
                    }

                    override fun onDenied() {
                        Log.e("Tag", "没权限2222")
                        //被拒绝
                        /*if (isFirstShowDialog){*/
                        val dialog = TextDialog(mContext)
                        dialog.setTitle("是否去开启相关权限", true)
                        dialog.setContent("拒绝给予权限会导致相关功能不能正常使用")
                        dialog.setOnBtnClickListener(object : TextDialog.OnBtnClickListener {
                            override fun confirm() {
                                isPermissionResult = true
                                val intent = Intent("android.settings.APPLICATION_DETAILS_SETTINGS")
                                intent.data = Uri.parse("package:" + Utils.getApp().packageName)
                                startActivity(
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
                                dialog.dismiss()

                            }

                            override fun cancel() {
                                dialog.dismiss()
                            }
                        })
                        dialog.show()
                        isFirstShowDialog = false
                        /*}*/
                    }
                })
                .rationale { shouldRequest -> shouldRequest!!.again(true) }
                .request()
        if (!GPSUtils.isOPen(mContext)) {
            GPSUtils.openGPS(mContext)
        }
    }

    override fun onResume() {
        super.onResume()
        if (isPermissionResult) {
            LocationManger.getInstance().setIsSendMsg(true)
            isPermissionResult = false
        }

        if (Constants.isLogin()) {
            ImageLoader.loadAvatar(mContext, iv_plus, Constants.getUserEntity()?.avatar)
        } else {
            iv_plus.setImageResource(R.color.colorDivler)
        }
    }

    /**
     * 当第一次没有给予定位权限 如果用户手动设置成功回调此方法
     * (仅在没给予权限后重获权限调用,仅调用一次)
     * @param isSuccess 接收从LocationManger发过来的消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun getLocationSuccessMsg(isSuccess: String?) {
        Log.e("Tag", "getLocationSuccessMsg")
        if ("location_success" == isSuccess) {
            currentPage = 1
            mLocationInfo = Constants.getLocation()
            getPresenter().loadData(currentPage.toString(), mLocationInfo[1], mLocationInfo[0], false)
            LocationManger.getInstance().setIsSendMsg(false)
        } else if ("用户资料加载成功" == isSuccess) {
            if (Constants.isLogin()) {
                ImageLoader.loadAvatar(mContext, iv_plus, Constants.getUserEntity()?.avatar)
            } else {
                iv_plus.setImageResource(R.color.colorDivler)
            }
        }
    }


    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        val offset = Math.abs(verticalOffset)
        val total = appBarLayout!!.totalScrollRange
        val alphaOut = if (130 - offset < 0) 0 else 140 - offset
        val maskColorIn = Color.argb(offset, Color.red(mMaskColor),
                Color.green(mMaskColor), Color.blue(mMaskColor))
        val maskColorInDouble = Color.argb(offset * 2, Color.red(mMaskColor),
                Color.green(mMaskColor), Color.blue(mMaskColor))
        val maskColorOut = Color.argb(alphaOut * 2, Color.red(mMaskColor),
                Color.green(mMaskColor), Color.blue(mMaskColor))
        if (offset <= total / 2) {
            tl_expand!!.visibility = View.VISIBLE
            tl_collapse!!.visibility = View.GONE
            v_expand_mask!!.setBackgroundColor(maskColorInDouble)
        } else {
            tl_expand!!.visibility = View.GONE
            tl_collapse!!.visibility = View.VISIBLE
            v_collapse_mask!!.setBackgroundColor(maskColorOut)
        }
        //v_pay_mask!!.setBackgroundColor(maskColorIn)
    }

    /**
     * 获取RecycleView的滑动距离
     */
    fun getSrollYDistance(): Int {
        val linearLayoutManager = rec_home.layoutManager as LinearLayoutManager
        val position = linearLayoutManager.findFirstVisibleItemPosition()
        val itemChildView = linearLayoutManager.findViewByPosition(position) ?: return 0
        return position * itemChildView.height - itemChildView.top
    }

    override fun setData(data: HomeEntity?, isLoadMore: Boolean) {
        fl_loading.visibility = View.GONE
        swipeRefreshLayout.isRefreshing = false
        rec_home.visibility = View.VISIBLE
        currentPage++
        if (!isLoadMore) {
            mHomeAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN)
            mHomeAdapter.setNewData(data?.recommend_list)
            initClassifyList(data?.category_list)
            Constants.putHomeData(data)

        } else {
            val recommend_list = data?.recommend_list
            if (recommend_list != null && recommend_list.size > 0) {
                mHomeAdapter.loadMoreComplete()
                mHomeAdapter.addData(recommend_list)
            } else {
                mHomeAdapter.loadMoreEnd()
            }
        }
    }

    override fun onDataFailure(msg: String?) {
        fl_loading.visibility = View.GONE
        swipeRefreshLayout.isRefreshing = false
        mHomeAdapter.loadMoreFail()
    }

    private fun initClassifyList(category_list: List<HomeEntity.CategoryListBean>?) {
        try {
            for (i in category_list!!.indices) {

                val view = mLl_container.getChildAt(i)
                ImageLoader.loadToUrl(mContext, view.iv_item_icon, Constants.getBaseUrl() + category_list[i].img)
                view.tv_item_title.text = category_list[i].category_name
                view.setOnClickListener { view ->
                    val intent = Intent(mContext, CategoryActivity::class.java)
                    intent.putExtra("category_id", category_list[view.id].category_id)
                    intent.putExtra("category_name", category_list[view.id].category_name)
                    startActivity(intent)
                }
            }
        } catch (e: Exception) {
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}